package cc.smarnet.caihou.phone.warehouse;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.smarnet.caihou.IPConfig;

import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.util.DateUtil;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 新增入库的activity
 */
public class WarehouseAddActivity extends AppCompatActivity {
    private ImageButton imageButton;
    private Spinner sourceBaseSpinner;//来源基地
    private Spinner sourceGreenhouseSpinner;//来源大棚
    private Spinner varietySpinner;//采收品种
    private TextView varietyCodeTextView;//品种编码;
    private Spinner packingSpecificationsSpinner;//打包规格
    private Spinner classesSpinner;//等级
    private Spinner flowerPoleLengthSpinner;//花杆长度
    private EditText tagNumEditText;//入库数量;
    private EditText sortTimeEditText;//分拣日期;
    private Button confirmButton;
    private ProgressBar progressBar;


    private String token;

    List<String> sourceBaseList = new ArrayList<>();
    List<String> sourceGreenhouseList = new ArrayList<>();
    List<String> varietyList = new ArrayList<>();
    List<String> varietyCodeList = new ArrayList<>();
    List<String> packingSpecificationsList = new ArrayList<>();
    List<String> classesList = new ArrayList<>();
    List<String> flowerPoleLengthList = new ArrayList<>();

    List<String> sourceBaseIdList = new ArrayList<>();
    List<String> sourceGreenhouseIdList = new ArrayList<>();


    private String sourceBaseId;//来源基地id
    private String sourceGreenhouseId;//来源大棚id
    private String variety;//采收品种
    private String varietyCode;//品种编码
    private String packingSpecifications;//打包规格
    private String classes;//等级
    private String flowerPoleLength;//花杆长度
    private int tagNum;//入库数量
    private String sortTime;//分拣日期

    int mYear, mMonth, mDay;

    private final String basePath = "/sys/dict/getDictItems";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warehouse_add);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        progressBar.setVisibility(View.GONE);

        sortTime= DateUtil.currentDate();
        sortTimeEditText.setText(sortTime);//设置默认的分拣日期

        getToken();
        /*
         * 获取基地的数据并设置在spinner中，然后再获取大棚的数据并设置在spinner。
         * 只有先有了基地的数据才能获取到相应大棚的数据
         * */
        getSourceBase();
        getVariety();//获取采收品种
        getPackingSpecifications();//获取打包规格
        getClasses();//获取等级
        getFlowerPoleLength();// 获取花杆长度

        getDate();// 获取当前的日期
        // 选择分拣日期的监听
        sortTimeEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(WarehouseAddActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int day) {
                                mYear = year;
                                mMonth = month;
                                mDay = day;
                                String transMonth = String.format("%02d", mMonth + 1);// 如果月份小于10的话进行补0
                                String transDay = String.format("%02d", mDay);// 如果日小于10的话进行补0
                                sortTime = mYear + "-" + transMonth + "-" + transDay;
                                sortTimeEditText.setText(sortTime);
                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
        });
        // 点击确认按钮的监听
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取入库数量
                if (tagNumEditText.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(WarehouseAddActivity.this).create();
                    alertDialog.setMessage("请输入入库数量！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                } else {
                    tagNum = Integer.valueOf(tagNumEditText.getText().toString());
                }

                // 获取分拣日期
                if (sortTimeEditText.getText().toString().equals("点击选择日期")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(WarehouseAddActivity.this).create();
                    alertDialog.setMessage("请选择分拣日期！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }

                // 新增入库信息
                addWarehouse();
            }
        });
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initViews() {
        imageButton = findViewById(R.id.warehouse_add_return);
        sourceBaseSpinner = findViewById(R.id.warehouse_add_sourceBase_spinner);
        sourceGreenhouseSpinner = findViewById(R.id.warehouse_add_sourceGreenhouse_spinner);
        varietySpinner = findViewById(R.id.warehouse_add_variety_spinner);
        varietyCodeTextView = findViewById(R.id.warehouse_add_varietyCode_textView);
        packingSpecificationsSpinner = findViewById(R.id.warehouse_add_packingSpecifications_spinner);
        classesSpinner = findViewById(R.id.warehouse_add_classes_spinner);
        flowerPoleLengthSpinner = findViewById(R.id.warehouse_add_flowerPoleLength_spinner);
        tagNumEditText = findViewById(R.id.warehouse_add_tagNum_editText);
        sortTimeEditText = findViewById(R.id.warehouse_add_sortTime_editText);
        confirmButton = findViewById(R.id.warehouse_confirm_add_button);
        progressBar = findViewById(R.id.warehouse_add_progressBar);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    // 获取基地
    public void getSourceBase() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/plantingBase/getAllBase";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(WarehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(WarehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                sourceBaseList.add(name);
                                sourceBaseIdList.add(jsonObj.getString("id"));
                            }

                            if (sourceBaseIdList.size() > 0) {// 如果sourceBaseIdList有值的话为sourceBaseSpinner赋值，然后获取第一个基地下大棚的数据
                                sourceBaseId = sourceBaseIdList.get(0);//设置默认的基地的id
                                sourceBaseSpinner();
                                getSourceGreenhouse(sourceBaseIdList.get(0));
                            }
                        }
                    }
                });
    }

    // 获取大棚
    public void getSourceGreenhouse(String sourceBaseId) {
        String url = IPConfig.baseUrl + "/flower/flowerPlantingGreenhouse/queryByParentId/" + sourceBaseId;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        /*Toast.makeText(warehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(warehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);*/
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        sourceGreenhouseList.clear();
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                sourceGreenhouseList.add(name);
                                sourceGreenhouseIdList.add(jsonObj.getString("id"));
                            }
                            if (sourceGreenhouseList.size() > 0) {
                                sourceGreenhouseId = sourceGreenhouseIdList.get(0);//设置默认大棚的id
                                sourceGreenhouseSpinner();
                            }
                        } else {
                            // 如果没有取到大棚的数据，那么弹窗提示，在弹窗中点击了确定按钮后，并且使确定按钮不可用
                            AlertDialog alertDialog = new AlertDialog.Builder(WarehouseAddActivity.this).create();
                            alertDialog.setMessage("所选基地无大棚信息，无法进行新增入库信息操作！");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    sourceGreenhouseSpinner();
                                    confirmButton.setClickable(false);
                                }
                            });
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取采收品种
    public void getVariety() {
        String url = IPConfig.baseUrl + "/flower/flowerVariety/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WarehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(WarehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                varietyList.add(name);
                                // 获取品种编码
                                String code=jsonObj.getString("code");
                                varietyCodeList.add(code);
                            }

                            if (varietyList.size() > 0) {
                                variety = varietyList.get(0);// 设置默认的采收品种
                                varietyCode = varietyCodeList.get(0);// 设置默认的品种编码
                                varietyCodeTextView.setText(varietyCode);
                                varietySpinner();
                            }
                        }
                    }
                });
    }

    // 获取打包规格
    public void getPackingSpecifications() {
        String url = IPConfig.baseUrl + basePath + "/planting_packing_specifications";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WarehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(WarehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                packingSpecificationsList.add(name);
                            }

                            if (packingSpecificationsList.size() > 0) {
                                packingSpecifications = packingSpecificationsList.get(0);// 设置默认的打包规格
                                packingSpecificationsSpinner();
                            }
                        }
                    }
                });
    }

    // 获取花卉等级
    public void getClasses() {
        String url = IPConfig.baseUrl + basePath + "/planting_flower_level";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WarehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(WarehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                classesList.add(name);
                            }

                            if (classesList.size() > 0) {
                                classes = classesList.get(0);// 设置默认的打包规格
                                classesSpinner();
                            }
                        }
                    }
                });
    }

    // 获取花杆长度
    public void getFlowerPoleLength() {
        String url = IPConfig.baseUrl + basePath + "/planting_flower_pole";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WarehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(WarehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                flowerPoleLengthList.add(name);
                            }

                            if (flowerPoleLengthList.size() > 0) {
                                flowerPoleLength = flowerPoleLengthList.get(0);// 设置默认的花杆长度
                                flowerPoleLengthSpinner();
                            }
                        }
                    }
                });
    }

    //来源基地的spinner
    public void sourceBaseSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, sourceBaseList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sourceBaseSpinner.setAdapter(adapter);
        sourceBaseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sourceBaseId = sourceBaseIdList.get(i);
                getSourceGreenhouse(sourceBaseId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //来源大棚的spinner
    public void sourceGreenhouseSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, sourceGreenhouseList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sourceGreenhouseSpinner.setAdapter(adapter);
        sourceGreenhouseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sourceGreenhouseId = sourceGreenhouseIdList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //采收品种的spinner
    public void varietySpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, varietyList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        varietySpinner.setAdapter(adapter);
        varietySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                variety = varietyList.get(i);

                varietyCode=varietyCodeList.get(i);
                varietyCodeTextView.setText(varietyCode);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //打包规格的spinner
    public void packingSpecificationsSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, packingSpecificationsList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        packingSpecificationsSpinner.setAdapter(adapter);
        packingSpecificationsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                packingSpecifications = packingSpecificationsList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //等级的spinner
    public void classesSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, classesList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        classesSpinner.setAdapter(adapter);
        classesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                classes = classesList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //花杆长度的spinner
    public void flowerPoleLengthSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, flowerPoleLengthList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        flowerPoleLengthSpinner.setAdapter(adapter);
        flowerPoleLengthSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                flowerPoleLength = flowerPoleLengthList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }


    // 新增入库信息
    public void addWarehouse() {
        progressBar.setVisibility(View.VISIBLE);
        confirmButton.setClickable(false);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sourceBase", sourceBaseId);//基地id
        map.put("sourceGreenhouse", sourceGreenhouseId);//大棚id
        map.put("variety", variety);//采收品种
        map.put("varietyCode", varietyCode);//品种编码
        map.put("packingSpecifications", packingSpecifications);//打包规格
        map.put("classes", classes);//等级
        map.put("flowerPoleLength", flowerPoleLength);//花杆长度
        map.put("tagNum", tagNum);//入库数量
        map.put("sortTime", sortTime);//采摘日期
        String requestJsonString = JSON.toJSONString(map);
        String url = IPConfig.baseUrl + "/flower/flowerTagIn/add";
        OkHttpUtils
                .postString()
                .addHeader("X-Access-Token", token)
                .url(url)
                .content(requestJsonString)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        confirmButton.setClickable(true);
                        Toast.makeText(WarehouseAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(WarehouseAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(WarehouseAddActivity.this).create();
                            alertDialog.setMessage("入库信息新增成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(WarehouseAddActivity.this, WarehouseActivity.class);
                                    startActivity(intent);
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取当前日期
    public void getDate() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }
}